package org.csu.mybigpro.controller;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import jakarta.annotation.Resource;
import org.csu.mybigpro.DTO.AssignmentUpdateDTO;
import org.csu.mybigpro.common.CommonResponse;
import org.csu.mybigpro.domain.Assignment;
import org.csu.mybigpro.properties.AssignmentProperties;
import org.csu.mybigpro.service.AssignmentService;
import org.csu.mybigpro.util.MinioUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/teacher/assignment")
public class AssignmentController {

    @Autowired
    private AssignmentService assignmentService;

    @Resource
    private AssignmentProperties assignmentProperties;

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioUtil minioUtil;

    @PostMapping("/publish")
    public CommonResponse<String> publishAssignment(
            @RequestParam("courseId") Long course_id,
            @RequestParam("title") String title,
            @RequestParam(value = "content", required = false) String content,
            @RequestParam("publishTime") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime publish_time,
            @RequestParam("deadline") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime deadline,
            @RequestParam("autoGrade") Boolean auto_grade,
            @RequestParam(value = "filePath", required = false) MultipartFile file
    ) {
        String filePath = null;
        // 如果上传了文件，就调用 MinioUtil 上传并获取 URL
        if (file != null && !file.isEmpty()) {
            try {
                // uploadFile 返回形如 http://host:port/bucketName/objectName 的访问链接
                filePath = minioUtil.uploadFile(file);
            } catch (Exception e) {
                System.out.println("上传到 MinIO 失败");
                return CommonResponse.createForError(400, "文件上传失败：" + e.getMessage());
            }
        }

        Assignment assignment = new Assignment();
        assignment.setId(null);                // 保证数据库自增
        assignment.setCourseId(course_id);
        assignment.setTitle(title);
        assignment.setContent(content);
        assignment.setFilePath(filePath);      // 存储 MinIO 上的 URL
        assignment.setPublishTime(publish_time);
        assignment.setDeadline(deadline);
        assignment.setAutoGrade(auto_grade);

        assignmentService.saveAssignment(assignment);

        Map<String, Object> data = new HashMap<>();
        data.put("assignment", assignment);

        return CommonResponse.createForSuccess("作业发布成功", data.toString());
    }



    // ✅ 查询单个
    @GetMapping("/{id}")
    public CommonResponse<Assignment> getAssignmentById(@PathVariable Long id) {
        return CommonResponse.createForSuccess(assignmentService.getAssignmentById(id));
    }

    // ✅ 查询全部
    @GetMapping("/list")
    public CommonResponse<List<Assignment>> getAllAssignments() {

        return CommonResponse.createForSuccess(assignmentService.getAllAssignments());
    }

    // ✅ 修改
    @PutMapping("/update")
    public CommonResponse<String> updateAssignment(
            @ModelAttribute AssignmentUpdateDTO dto,
            @RequestParam(value = "filePath", required = false) MultipartFile file
    ) {
        Assignment existing = assignmentService.getAssignmentById(dto.getId());
        if (existing == null) {
            return CommonResponse.createForError(404, "作业不存在");
        }

        // 只更新非 null 字段
        if (dto.getCourseId() != null) existing.setCourseId(dto.getCourseId());
        if (dto.getTitle() != null) existing.setTitle(dto.getTitle());
        if (dto.getContent() != null) existing.setContent(dto.getContent());
        if (dto.getPublishTime() != null) existing.setPublishTime(dto.getPublishTime());
        if (dto.getDeadline() != null) existing.setDeadline(dto.getDeadline());
        if (dto.getAutoGrade() != null) existing.setAutoGrade(dto.getAutoGrade());

        if (file != null && !file.isEmpty()) {
            try {
                // 使用MinioUtil上传文件到Minio桶
                String url = minioUtil.uploadFile(file);
                existing.setFilePath(url);
            } catch (Exception e) {
                return CommonResponse.createForError(500, "文件上传失败：" + e.getMessage());
            }
        }

        assignmentService.updateAssignment(existing);
        return CommonResponse.createForSuccess("作业更新成功");
    }




    // ✅ 删除
    @DeleteMapping("/delete/{id}")
    public CommonResponse<String> deleteAssignment(@PathVariable Long id) {
        assignmentService.deleteAssignment(id);
        return CommonResponse.createForSuccess("删除成功");
    }
}
